<template>
  <div>
       <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card> 
    <el-alert
    title="注意：只允许为第三级分类设置相关参数！"
    type="warning"
    :closable="false"
    show-icon> </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 选择商品分类的级联选择框 -->
          <el-cascader expand-trigger="hover" :options="catesList" :props="cateProps" v-model="selectedCateKeys" @change="handleChange">
          </el-cascader>
        </el-col>
      </el-row>
    <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="动态参数" name="many">
        <el-button type="primary" size="mini" :disabled="!isSelected" @click="addDialogVisible=true">添加参数</el-button>
    <el-table
    :data="manyTableData"
    border
    stripe
    style="width: 80%">
    <el-table-column type="expand">
      <template slot-scope="scope">
        <el-tag v-for="(val,index) in scope.row.attr_vals_list" :key="index" closable="true" @close="deleteAttr(index,scope.row)">{{val}}</el-tag>
  <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

      </template>
    </el-table-column>
    <el-table-column type="index" label="#"></el-table-column>
    <el-table-column
      prop="attr_name"
      label="参数名称">
    </el-table-column>
    <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditDialog(scope.row)">编辑</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParam(scope.row)">删除</el-button>
        </template>
    </el-table-column>
    </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
        <el-button type="primary" size="mini" :disabled="!isSelected" @click="addDialogVisible=true">添加属性</el-button>
          <el-table
    :data="onlyTableData"
    border
    stripe
    style="width: 80%">
    <el-table-column type="expand">
       <template slot-scope="scope">
        <el-tag v-for="(val,index) in scope.row.attr_vals_list" :key="index" closable="true" @close="deleteAttr(index,scope.row)">{{val}}</el-tag>
  <el-input
  class="input-new-tag"
  v-if="scope.row.inputVisible"
  v-model="scope.row.inputValue"
  ref="saveTagInput"
  size="small"
  @keyup.enter.native="handleInputConfirm(scope.row)"
  @blur="handleInputConfirm(scope.row)"
>
</el-input>
<el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>

      </template>
    </el-table-column>
    <el-table-column type="index" label="#"></el-table-column>
    <el-table-column
      prop="attr_name"
      label="属性名称">
    </el-table-column>
    <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" icon="el-icon-edit"  @click="showEditDialog(scope.row)">编辑</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteParam(scope.row)">删除</el-button>
        </template>
    </el-table-column>
    </el-table>
    </el-tab-pane>
  </el-tabs>
    </el-card>
    <el-dialog :title="'添加'+textTitle" :visible.sync="addDialogVisible" width="30%" @close="clearAddForm">
   <el-form :model="addForm" :rules="addFormRule" ref="addFormRef" label-width="28%">
    <el-form-item :label="textTitle+'名称'" prop="attr_name">
      <el-input v-model="addForm.attr_name"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="addDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addParams">确 定</el-button>
  </div>
</el-dialog>
 <el-dialog :title="'修改'+textTitle" :visible.sync="editDialogVisible" width="30%" @close="clearEditForm">
   <el-form :model="editForm" :rules="editFormRule" ref="editFormRef" label-width="28%">
    <el-form-item :label="textTitle+'名称'" prop="attr_name">
      <el-input v-model="editForm.attr_name"></el-input>
    </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editParams">确 定</el-button>
  </div>
</el-dialog>
  </div>
</template>

<script>
import request from '../../api/index'
export default {
    name:'Params',
    data(){
        return {
            catesList:[],
            cateProps:{
                label:'cat_name',
                value:'cat_id',
                children:'children'
            },
            activeName:'many',
            selectedCateKeys:[],
             // 动态参数的数据
            manyTableData: [],
             // 静态属性的数据
            onlyTableData: [],
            addDialogVisible:false,
            addForm:{
                attr_name:''
            },
            addFormRule:{
                attr_name:[
                    {required:true,message:"请填写名称！",trigger:'blur'}
                ]
            },
            editDialogVisible:false,
            editForm:{
              attr_name:'',
              cat_id:'',
              attr_id:'',
              attr_sel:'',
              attr_vals:''
            },
            editFormRule:{
              attr_name:[
                {required:true,message:'名称不能为空！',trigger:'blur'}
              ]
            },
            
        }
    },
    computed:{
        isSelected(){
            return this.selectedCateKeys.length==3
        },
        cateId(){
            if(this.isSelected==true){
                return this.selectedCateKeys[2]
            }
            return null
        },
        textTitle(){
            return this.activeName=="many"?'动态参数':'静态属性'
        }
    },
    created(){
        this.getCatesList()
    },
    methods: {
      async  getCatesList(){
          const {data:res}=await request({url:'/categories',method:'get',data:{type:3}})
          if(res.meta.status!==200){
              this.$message.error("获取商品分类失败！")
          }
          this.catesList=res.data
        },
        async getParamsData(){
            const {data:res}=await request({url:`/categories/${this.cateId}/attributes`,method:'get',
            params:{sel:this.activeName}})
                if (res.meta.status !== 200) {
            return this.$message.error('获取参数列表失败！')
             }
             res.data.forEach((item)=>{
               item.attr_vals_list=item.attr_vals?item.attr_vals.split(' '):[]
               item.inputVisible=false
               item.inputValue=''
             })

            console.log(res.data)
            if (this.activeName === 'many') {
            this.manyTableData = res.data
            } else {
            this.onlyTableData = res.data
            }
        },
        // Tab切换
        handleClick(){
            this.getParamsData()
        },
        //级联选择切换
        handleChange(){
            console.log(this.selectedCateKeys)
            this.getParamsData()
        },
        clearAddForm(){
            this.$refs.addFormRef.resetFields()
        },
       async addParams(){
           const {data:res}=await request({url:`/categories/${this.cateId}/attributes`,method:'post',
            data:{attr_name:this.addForm.attr_name,attr_sel:this.activeName}})
            if(res.meta.status!=201){
                return this.$message.error("添加失败！")
            }
            this.$message.success("添加成功！")
            this.addDialogVisible=false
              this.getParamsData()
        },
        showEditDialog(row){
          this.editForm.attr_name=row.attr_name
          this.editForm.attr_id=row.attr_id
          this.editForm.cat_id=row.cat_id
          this.editForm.attr_sel=row.attr_sel
          this.editForm.attr_vals=row.attr_vals
          console.log(this.editForm)
        
          this.editDialogVisible=true
        },
        clearEditForm(){
          this.$refs.editFormRef.resetFields()
        },
        async editParams(){
            const {data:res}=await request({url:`/categories/${this.editForm.cat_id}/attributes/${this.editForm.attr_id}`,
            method:'put',data:{attr_name:this.editForm.attr_name,attr_sel:this.editForm.attr_sel,
            attr_vals:this.editForm.attr_vals}})
            if(res.meta.status!==200)
            return this.$message.error("编辑失败！")
            else{
              this.$message.success("编辑成功！")
              this.getParamsData()
              this.editDialogVisible=false
            }
        },
          async  deleteParam(row){
         let result=await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).catch(err=>err)
        if(result!=='confirm')
          return this.$message.info("已取消删除！")
        const {data:res}=await request({url:`/categories/${row.cat_id}/attributes/${row.attr_id}`,
                          method:'delete'})
         if(res.meta.status!==200)
         {
            this.$message.error("删除失败！")
         }
            this.getParamsData()
           this.$message.success("删除成功！")
    },

       handleClose(tag) {
        this.dynamicTags.splice(this.dynamicTags.indexOf(tag), 1);
      },

      showInput(row) {
        row.inputVisible = true;
        console.log('haha')
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },

      handleInputConfirm(row) {
        if(row.inputValue.trim().length===0){
          row.inputVisible=false;
          row.inputValue=" "
          return
        }
        row.attr_vals_list.push(row.inputValue.trim())
        row.inputValue=""
        row.inputVisible=false
        this.saveAttrVals(row)
      },
      async saveAttrVals(row){
        const { data: res } = await request({
          url:`categories/${this.cateId}/attributes/${row.attr_id}`,
          method:'put',
          data:{
          attr_name: row.attr_name,
          attr_sel: row.attr_sel,
          attr_vals: row.attr_vals_list.join(' ')
        }}
      )

      if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }

      this.$message.success('修改参数项成功！')
      },
      deleteAttr(index,row){
        row.attr_vals_list.splice(index,1)
        this.saveAttrVals(row)
      }
    
    

}}
</script>

<style>
.cat_opt{
    margin-top: 20px;
}
.el-card{
    margin-top:15px;
}
.el-tag{
  margin: .125rem;
}
 .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px !important;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>